package com.gxa.jjty.cjr.controller;

import com.gxa.jjty.cjr.service.AddressService;
import com.gxa.jjty.core.common.ExceptionCode;
import com.gxa.jjty.core.exception.BusinessException;
import com.gxa.jjty.core.group.AddGroup;
import com.gxa.jjty.core.group.UpdateGroup;
import com.gxa.jjty.core.pojo.Address;
import com.gxa.jjty.core.util.StringUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 *
 * @author : 宸濯
 * Date: 2021/12/07 15:08
 * Description:
 * Version: V1.0
 */

@Api(tags = "用户地址api")
@RestController
@RequestMapping("/address")
public class AddressController {

    @Autowired
    private AddressService addressService;

    @ApiOperation("添加用户地址")
    @PostMapping("/insert")
    public Map<String,Object> insert(@Validated(AddGroup.class) Address address) throws BusinessException {
        if (!StringUtil.isPhoneNumber(address.getPhone())){
            throw new BusinessException(ExceptionCode.BAD_PHONE);
        }
        return addressService.insert(address);
    }

    @ApiOperation("修改用户地址")
    @PostMapping("/update")
    public Map<String,Object> update(@Validated(UpdateGroup.class) Address address) throws BusinessException {
        if (address.getPhone()!=null && !StringUtil.isPhoneNumber(address.getPhone())){
            throw new BusinessException(ExceptionCode.BAD_PHONE);
        }
        if(address.getAddressPrimary()==null){
            throw new BusinessException(ExceptionCode.ERROR);
        }
        return addressService.update(address);
    }

    @ApiOperation("删除用户地址")
    @PostMapping("/delete")
    public Map<String,Object> delete(Long id) throws BusinessException {
        if (id==null){
            throw new BusinessException(ExceptionCode.NOT_NULL);
        }
        return addressService.delete(id);
    }

    @ApiOperation("根据用户id查询用户地址")
    @PostMapping("/selectById")
    public Map<String,Object> selectById(Long id) throws BusinessException {
        if (id==null){
            throw new BusinessException(ExceptionCode.NOT_NULL);
        }
        return addressService.selectById(id);
    }

    @PostMapping("/selectAddressPrimary")
    @ApiOperation("根据用户id查询默认地址")
    public Map<String, Object> selectAddressPrimary(Long id) throws BusinessException{
        if (id==null){
            throw new BusinessException(ExceptionCode.ID_NOTNULL);
        }
        return addressService.selectAddressPrimary(id);
    }


}
